<?php
/**
 * Author: LCY<409028735@qq.com>
 * Time: 2021/11/19 14:42
 * Note:
 */
namespace app\admin\model;
use think\facade\Config;
use think\facade\Session;
use think\Model;

class AdminLog extends Model
{
    /**
     * 保存管理员操作日志
     * @param int $admin_id  管理员id
     * @param string $title 标题
     * @param string $desc  描述信息
     * @param array $datas  保存数据
     * Author: LCY<409028735@qq.com>
     * Time: 2021/4/21 16:56
     * Note:
     */
    public static function saveAdminLog($admin_id = 0, $title = '', $desc = '', $datas = [])
    {
        $datas = $datas ? : input('post.');
        //密码字段隐藏
        if(is_array($datas) && isset($datas['password'])) {
            $datas['password'] = '***';
        }
        $url = request()->url();
        $data = [
            'admin_id' => $admin_id ? $admin_id : Session::get('user.id', Config::get('auth.AUTH_USER').'_'),
            'title' => self::getLogTitle($title, $url),
            'desc' => $desc,
            'url' => $url,
            'ip' => request()->ip(),
            'datas' => is_string($datas) ? $datas : json_encode($datas,JSON_UNESCAPED_UNICODE),
        ];
        self::create($data);
    }

    /**
     * 分析url，获取日志标题名称
     * @param string $title
     * @param $url
     * @return string
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/2 17:59
     * Note:
     */
    private static function getLogTitle($title = '', $url)
    {
        if(!empty($title)) {
            return $title;
        }
        if(false !== strrpos($url, 'add')) {
            $title = '添加';
        }elseif(false !== strrpos($url, 'edit')) {
            $title = '修改';
        }elseif(false !== strrpos($url, 'del')) {
            $title = '删除';
        }elseif(false !== strrpos($url, 'sort')) {
            $title = '排序';
        }elseif(false !== strrpos($url, 'toggle')) {
            $title = '切换';
        }

        return $title;
    }
}